package controllers;

import play.*;
import play.cache.Cache;
import play.i18n.Messages;
import play.libs.Codec;
import play.libs.Images;
import play.mvc.*;

import java.util.*;

import models.*;

public class Application extends Controller {
	/**
	 * 全局页面初始化：重新检查或缓存当前用户对象
	 */
	public static String yongHuKey;
	public static String YONG_HU_ID="YONG_HU_ID";
    @Before
    static void quanJu() {
    	//从缓存中获取当前登录的用户对象
        YongHu yongHu = dangQianYongHu();
        if(yongHu==null){//如果当前登录的用户对象已经失效
        	//从当前会话中获取用户的id，重新获取用户对象，和当前会话id绑定放入缓存
        	String yongHuId = session.get(YONG_HU_ID);//YONG_HU_ID是在用户登录的时候被放入session中的
        	if(yongHuId!=null){
        		yongHuKey=session.getId() + "-yongHu";
        		Cache.set(yongHuKey, YongHu.findById(yongHuId));
        	}
        }
    }
    /**
     * 对标注了AnQuan的方法进行安全检查
     */
    @Before
    static void anQuanJianCha() {
        AnQuan anQuan = getActionAnnotation(AnQuan.class);
        if (anQuan != null) {
        	YongHu yongHu=dangQianYongHu();
            if (yongHu== null)	forbidden();
            else{
            	if(anQuan.admin()&&!yongHu.shiGuanLiYuan())
            		forbidden();
            	if(!anQuan.shiTi()&&!yongHu.youQuanXian(request.action))
            		forbidden();
           		if(anQuan.shiTi()&&yongHu.youQuanXian(request.action,
           				(ShiTi)request.args.get(anQuan.SHI_TI)));
           			forbidden();
           		//TODO 接下来是否需要处理SHI_TI为数组的情况
            }
        }
    }
    /**
     * 返回缓存中获取当前登录的用户对象
     * @return YongHu
     */
    public static YongHu dangQianYongHu() {
    	yongHuKey=session.getId() + "-yongHu";
    	return Cache.get(yongHuKey,YongHu.class);
    }

    
    public static void index() {
        render();
    }
    public static void captcha(String id) {
        Images.Captcha captcha = Images.captcha();
        String code = captcha.getText("#E4EAFD");
        Cache.set(id, code, "10mn");
        renderBinary(captcha);
    }
/*    public static void show(Long id) {
        //Post post = Post.findById(id);
        String randomID = Codec.UUID();
        //render(post, randomID);
    }*/


}